// 打卡页面逻辑
Page({
  data: {
    // 当前选择的日期
    currentDate: '',
    currentDateStr: '',
    
    // 已打卡日期
    checkinDates: [],
    
    // 学习统计数据
    stats: {
      newWords: 0,
      reviewWords: 0,
      accuracy: 0
    },
    
    // 心得选择相关数据
    selectedThought: 0,
    thoughtContents: [
      "",
      "今天又掌握了一批新单词，坚持学习的感觉真好！英语学习是一场持久战，我会一步一个脚印地前进。",
      "今日词汇学习完成，有些单词很有挑战性，但我坚持攻克了难点。每天进步一点点，终会积累成大不同！",
      "今天的学习效率不错，新词记忆和复习都很顺利。好的学习习惯让英语之路越走越宽，继续保持！",
      "单词学习并不总是枯燥的，今天通过例句情境记忆了许多有趣表达。享受学习过程，知识才能真正内化。"
    ],
    
    // 最大字数限制（保留备用）
    maxLength: 140,
    
    // 已选择的图片列表
    uploadedImages: [],
    
    // 是否已分享打卡
    hasShared: false,
    
    // 是否显示日历选择器
    showCalendar: false,
    
    // 日历配置
    calendarConfig: {
      showTitle: false,
      showConfirm: false,
      markCalendar: []
    }
  },
  
  onLoad: function() {
    this.setCurrentDate();
    this.loadCheckinDates();
  },
  
  onShow: function() {
    // 每次页面显示时更新数据
    this.loadCheckinDates();
    this.loadCurrentDateData();
  },
  
  // 设置当前日期
  setCurrentDate: function() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const dateString = `${year}-${month}-${day}`;
    
    this.setData({
      currentDate: dateString,
      currentDateStr: dateString
    });
  },
  
  // 加载打卡日期记录
  loadCheckinDates: function() {
    // 从本地存储加载所有学习记录日期
    const dailyProgress = wx.getStorageSync('dailyProgress') || {};
    
    // 获取所有有学习记录的日期
    const checkinDates = Object.keys(dailyProgress).filter(date => {
      // 只记录有学习进度的日期
      return dailyProgress[date].completed > 0;
    }).sort();
    
    this.setData({
      checkinDates: checkinDates
    });
    
    this.formatCheckinDates();
  },
  
  // 格式化打卡日期为日历标记格式
  formatCheckinDates: function() {
    const marks = this.data.checkinDates.map(date => {
      return {
        date: date,
        type: 'success'
      };
    });
    
    this.setData({
      'calendarConfig.markCalendar': marks
    });
  },
  
  // 显示日历
  toggleCalendar: function() {
    this.setData({
      showCalendar: !this.data.showCalendar
    });
  },
  
  // 选择日期
  onDateSelect: function(e) {
    const date = e.detail.value; // 原生picker返回YYYY-MM-DD格式
    this.setData({
      currentDate: date,
      showCalendar: false
    });
    
    // 根据选择日期加载对应数据
    this.loadDateData(date);
  },
  
  // 加载当前选择日期的数据
  loadCurrentDateData: function() {
    this.loadDateData(this.data.currentDate);
  },
  
  // 加载指定日期的数据
  loadDateData: function(date) {
    console.log('加载日期数据', date);
    
    // 从本地存储加载数据
    const dailyProgress = wx.getStorageSync('dailyProgress') || {};
    const dailyData = dailyProgress[date] || { completed: 0, total: 50 };
    
    // 从全局获取学习数据
    const app = getApp();
    const studyData = app.globalData.studyData || {
      totalWords: 0,
      masteredWords: 0
    };
    
    // 从本地存储获取当天的详细学习记录
    const dailyDetails = wx.getStorageSync('dailyDetails') || {};
    const details = dailyDetails[date] || {
      newWords: 0,
      reviewWords: 0,
      correctCount: 0,
      totalAnswered: 0
    };
    
    // 计算正确率
    const accuracy = details.totalAnswered > 0 
      ? Math.round((details.correctCount / details.totalAnswered) * 100) 
      : 0;
    
    // 设置学习统计数据
    this.setData({
      stats: {
        newWords: details.newWords || dailyData.completed || 0,
        reviewWords: details.reviewWords || 0,
        accuracy: accuracy
      },
      hasShared: this.data.checkinDates.includes(date)
    });
    
    // 如果是当天有记录但没有详细数据，使用默认值
    if (dailyData.completed > 0 && !details.newWords) {
      // 假设70%是新学，30%是复习
      const newWords = Math.round(dailyData.completed * 0.7);
      const reviewWords = Math.round(dailyData.completed * 0.3);
      
      // 模拟85%的正确率
      const accuracy = 85;
      
      this.setData({
        stats: {
          newWords: newWords,
          reviewWords: reviewWords,
          accuracy: accuracy
        }
      });
      
      // 保存到本地存储
      dailyDetails[date] = {
        newWords: newWords,
        reviewWords: reviewWords,
        correctCount: Math.round((newWords + reviewWords) * (accuracy / 100)),
        totalAnswered: newWords + reviewWords
      };
      
      wx.setStorageSync('dailyDetails', dailyDetails);
    }
    
    // 加载心得内容
    const thoughts = wx.getStorageSync('dailyThoughts') || {};
    const thought = thoughts[date] || '';
    
    // 根据保存的心得内容找到对应的选项
    let selectedId = 0;
    for (let i = 1; i < this.data.thoughtContents.length; i++) {
      if (this.data.thoughtContents[i] === thought) {
        selectedId = i;
        break;
      }
    }
    
    this.setData({
      selectedThought: selectedId
    });
  },
  
  // 选择心得
  selectThought: function(e) {
    const id = Number(e.currentTarget.dataset.id);
    this.setData({
      selectedThought: id
    });
  },
  
  // 分享打卡
  shareCheckin: function() {
    if (this.data.selectedThought === 0) {
      wx.showToast({
        title: '请选择一条心得',
        icon: 'none'
      });
      return;
    }
    
    // 获取选中的文案
    const thoughtContent = this.data.thoughtContents[this.data.selectedThought];
    
    // 保存心得内容
    const date = this.data.currentDate;
    const thoughts = wx.getStorageSync('dailyThoughts') || {};
    thoughts[date] = thoughtContent;
    wx.setStorageSync('dailyThoughts', thoughts);
    
    // 模拟分享功能
    wx.showLoading({
      title: '生成分享图...',
    });
    
    setTimeout(() => {
      wx.hideLoading();
      
      wx.showToast({
        title: '打卡成功',
        icon: 'success',
        duration: 2000
      });
      
      // 更新打卡状态
      this.setData({
        hasShared: true
      });
      
      // 如果是当天打卡，更新全局数据
      const today = new Date().toISOString().split('T')[0];
      if (date === today) {
        const app = getApp();
        if (app.globalData.studyData) {
          app.globalData.studyData.streakDays = (app.globalData.studyData.streakDays || 0) + 1;
        }
      }
      
      // 模拟分享给朋友
      wx.showShareMenu({
        withShareTicket: true,
        menus: ['shareAppMessage', 'shareTimeline']
      });
    }, 1500);
  },
  
  // 上传图片
  uploadImage: function() {
    if (this.data.uploadedImages.length >= 3) {
      wx.showToast({
        title: '最多上传3张图片',
        icon: 'none'
      });
      return;
    }
    
    wx.chooseImage({
      count: 1,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success: (res) => {
        const tempFilePaths = res.tempFilePaths;
        
        // 将新选择的图片添加到列表
        this.setData({
          uploadedImages: [...this.data.uploadedImages, tempFilePaths[0]]
        });
      }
    });
  },
  
  // 删除已选择的图片
  deleteImage: function(e) {
    const index = e.currentTarget.dataset.index;
    const images = this.data.uploadedImages;
    images.splice(index, 1);
    
    this.setData({
      uploadedImages: images
    });
  }
})